package chixing.day12.work.w1;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Library {
    private static Library instance;
    private List<Book> books;
    public Library() {
        books = new ArrayList<>();
    }
    public static  Library getInstance() {
        if (instance == null) {
            instance = new Library();
        }
        return instance;
    }

    public void addBook(Book book) {
            books.add(book);
            System.out.println("图书《" + book.getTitle() + "》添加成功！");
    }
    public void removeBook(String title) {
     /*   for (int i = 0; i < books.size(); i++) {
            if (books.get(i).getTitle().equals(title)) {
                books.remove(i);
                System.out.println("图书《" + title + "》删除成功！");
            } else {
                System.out.println("未找到图书《" + title + "》，删除失败！");
            }
            }*/
        Iterator<Book> it = books.iterator();
        while(it.hasNext()) {
            Book book = it.next();
            if (book.getTitle().equals(title))
                it.remove();

        }
    }

    public List<Book> findBooks(String keyword) {
        if (books.isEmpty()) {
            return null;
        }
        List<Book> result = new ArrayList<>();
        if (keyword == null || keyword.isEmpty()) {
            return result;
        }

        for (Book book : books) {
            if (book.getTitle().contains(keyword) ||
                    book.getAuthor().contains(keyword)) {
                result.add(book);
            }
        }
        return result;
    }

    public void displayAllBooks() {

        System.out.println("\n图书馆中的图书列表：");
        System.out.println("====================");
        for (Book book : books) {
            System.out.println(book);
        }
        System.out.println("====================");
    }
}

